<template>
  <div class="login-wrap">
    <div class="ms-login">
      <div class="ms-title">登录</div>登录
      <el-form :model="param" :rules="rules" ref="login" label-width="0px" class="ms-content">
        <el-form-item prop="username">
          <el-input v-model="param.username" placeholder="用户名"  >
            <el-button slot="prepend" icon="el-icon-lx-people"></el-button>
          </el-input>
        </el-form-item>
        <el-form-item prop="密码">
          <el-input
            type="password"
            placeholder="password"
            v-model="param.password"
            @keyup.enter.native="submitForm()"
          >
            <el-button slot="prepend" icon="el-icon-lx-lock"></el-button>
          </el-input>
        </el-form-item>
        <template style='margin-bottom: 5px'>
          <!-- `checked` 为 true 或 false -->
          <el-checkbox v-model="checked">记住用户名密码</el-checkbox>
        </template>
        <div class="login-btn">
          <el-button type="primary" @click="submitForm()">登录</el-button>
        </div>
        <div class="login-btn">
          <el-button type="" @click="toPath()">注册</el-button>
        </div>
        <p class="login-tips">Tips : 用户名和密码不能为空。</p>
      </el-form>
      <!--            <p v-show='editVisible' class="login-tips">Tips : 登陆加载中...</p>-->
      <el-progress
        v-show='editVisible'
        :text-inside="true"
        :stroke-width="15"
        :percentage="percentage"
        :color="colors">
      </el-progress>

    </div>

    <el-dialog title="登录" :visible.sync="dialogFormVisible">
      <el-form :model="regList" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="用户名" :label-width="formLabelWidth" style="width: 70%">
          <el-input v-model="regList.username" autocomplete="off" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="密码" :label-width="formLabelWidth" style="width: 70%">
          <el-input v-model="regList.password" type="password" placeholder="请输入密码" @blur="checkValidate1(regList.password)"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email" :label-width="formLabelWidth" style="width: 70%">
          <el-input v-model="regList.email" class="email" placeholder="邮箱" @blur="checkValidate(regList.email)"></el-input>
        </el-form-item>
        <el-form-item label="验证码" :label-width="formLabelWidth" style="width: 70%">
          <el-input v-model="regList.code" placeholder="请输入验证码"></el-input>
          <button @click="getCode()" class="code-btn" :disabled="!show">
            <span v-show="show">发送验证码</span>
            <span v-show="!show" class="count">{{count}} s</span>
          </button>
        </el-form-item>
          <el-button @click="regFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveEdit">确 定</el-button>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
const TIME_COUNT =60//设置一个全局的倒计时的时间
export default {
  data: function() {
    return {
      yanzma: '',
      count: '',
      show: true,
      formLabelWidth: '120px',
      regList: {
        email: '',
        code: '',
        username: '',
        password: '',
        phone: '',
        authCode: '',
        randomCode: ''
      },
      dialogFormVisible: false,
      param: {
        username: localStorage.getItem('username'),
        password: localStorage.getItem('password'),
      },
      rules: {
        username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
      }
      ,checked:false,
      editVisible:false,
      percentage: 20,//vue加载盘得百分比值,
      colors: [
        {color: '#f56c6c', percentage: 20},
        {color: '#e6a23c', percentage: 40},
        {color: '#5cb87a', percentage: 60},
        {color: '#1989fa', percentage: 80},
        {color: '#6f7ad3', percentage: 100}
      ]
    };
  },
  methods: {
    // 保存编辑
    saveEdit() {
      console.log("登陆")
      console.log(this.$data.yanzma)
      // if (this.regList.code === ''){
      //   this.$message.error('请先输入验证码再点击注册')
      // }else {
      //   var yanzma=this.yanzma;
      //   var code=this.regList.code;
      //   this.$http({
      //     url:"/user/selectEmail",
      //     method:'post',
      //     params:{
      //       email:this.regList.email
      //     }
      //   }).then(data=>{
      //     if (data==null || data==''){
      //       // console.log(111111111)
      //       if(yanzma == code){
      //         this.$http({
      //           url:'user/Userinsert',
      //           method:'post',
      //           params:{
      //             username:this.regList.username,
      //             password:this.regList.password,
      //             phone:this.regList.phone,
      //             email:this.regList.email
      //           }
      //         }).then(res=>{
      //           if(res==1){
      //             this.$message.success("注册成功")
      //           }else {
      //             this.$message.warning("注册失败")
      //           }
      //         })
      //         this.regFormVisible = false;
      //       }else {
      //         this.$message.warning("验证码不正确")
      //       }
      //     }else {
      //       this.$message.warning("该邮箱已存在")
      //     }
      //   })
      // }


    },
    // 向后端发请求的点击事件
    getCode () {
      let _this = this
      if (this.regList.email === '') {
        _this.$message.error('请先输入邮箱再点击获取验证码')
      } else {
        if (this.regList.username === ''){
          _this.$message.error('请先输入用户名')
        }else {
          if (this.regList.password === ''){
            _this.$message.error('请先输入密码')
          }else{
            console.log(this.regList.email)
            console.log("邮箱")
            this.$http({
              url: '/front/mail/getCheckCode',
              method: 'post',
              params: { email:this.regList.email  }
            }).then(res=> {
              console.log("返回直")
              console.log(res.data)
              this.$data.yanzma=res.data;
              //这里我没用redis做缓存，用的浏览器sessionStorage+md5加密存下来的
            })
            // 验证码倒计时
            if (!this.timer) {
              this.count = TIME_COUNT
              this.show = false
              this.timer = setInterval(() => {
                if (this.count > 0 && this.count <= TIME_COUNT) {
                  this.count--
                } else {
                  this.show = true
                  clearInterval(this.timer)
                  this.timer = null
                }
              }, 1000)
            }
          }

        }
      }
    },
    checkValidate(value){
      if (!value) {
        // callback(new Error('邮箱不可为空'))
        this.$message({
          message: '邮箱不可为空!',
          type: 'error'
        });
      } else {
        if (value !== '') {
          let reg = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
          if (!reg.test(value)) {
            this.$message({
              message: '请输入格式正确有效的邮箱号',
              type: 'error'
            });
            // callback(new Error('请输入格式正确有效的邮箱号'))
          }
        }
        // callback()
      }
    },
    submitForm() {
        this.$http({
          method:'post',
          url:'/oauth/oauth/token',
          params:
            {username: this.param.username,
              password: this.param.password,
              grant_type:'password',
              client_id:'front',
              client_secret:'123'
            }
        }).then((res)=>{
          if(res.access_token !==undefined){

            // 保存用户信息
            // Storage只能存储字符串
            // localStorage 本地全局作用域，浏览器关闭再打开，local存在
            // sessionStorage 浏览器，浏览器关闭再打开，不存在
            // $store 刷新情况
            // code,msg,data{token principal}
            if(true){
              this.$message({
                type:'success',
                duration:5000,//显示时间
                message:'登陆成功加载中....'
              })
              sessionStorage.setItem('token',res.access_token)
              sessionStorage.setItem('username',this.param.username)
              sessionStorage.setItem('password',this.param.password)
              this.editVisible=true;
              let time=setInterval(()=>{
                if(this.percentage!=100){
                  this.percentage+=1
                }else {
                  this.$router.push('/');
                  //
                  clearInterval(time)
                }
                //this.$router.push('/dashboard');

              },40)
              if(this.checked==true){
                localStorage.setItem('username',this.param.username)
                localStorage.setItem('password',this.param.password)
              }else {
                localStorage.clear()
              }
            }else if(data.code == 501){
              this.$message.error(data.msg);
            }
            this.$router.push({path:'/'})

          }else {
            this.$message.error('用户名或密码错误')
          }
        })
      },
    toPath(){
      this.dialogFormVisible=true
    }
  }
};
</script>

<style>
.login-wrap {
  position: absolute;
  width: 100%;
  height: 100%;
  background-size: 100%;
}
.ms-title {
  width: 100%;
  line-height: 50px;
  text-align: center;
  font-size: 20px;
  color: #fff;
  border-bottom: 1px solid #ddd;
}
.ms-login {
  position: absolute;
  left: 50%;
  top: 50%;
  width: 350px;
  margin: -190px 0 0 -175px;
  border-radius: 5px;
  background: rgba(255, 255, 255, 0.3);
  overflow: hidden;
}
.ms-content {
  padding: 30px 30px;
}
.login-btn {
  text-align: center;
}
.login-btn button {
  width: 100%;
  height: 36px;
  margin-bottom: 10px;
}
.login-tips {
  font-size: 12px;
  line-height: 30px;
  color: #fff;
}
</style>
